<script setup>
import { ref } from "vue";
import Avatar from '@/components/Avatar.vue'
import {ElMessage} from "element-plus";
import { Camera } from '@element-plus/icons-vue';
import { userAPI } from '@/apis/user.js';
import { useUserStore } from '@/stores/user.js';

const emit = defineEmits(['resetUserInfo']);

const userStore = useUserStore();
const dialogVisible = ref(false)

const formData = ref({
  nickName: '',
  gender: 0,
  personDescription: '',
  avatar: null
});
const formDataRef = ref(null);

// 表单验证规则
const formRules = ref({
  nickName: [
    { required: true, message: 'Please input nickname', trigger: 'blur' },
    { min: 1, max: 8, message: 'Nickname length should be 1-8 characters', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9\u4e00-\u9fa5_-]+$/, message: 'Nickname can only contain letters, numbers, Chinese characters, underscores and hyphens', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: 'Please select gender', trigger: 'change' }
  ],
  personDescription: [
    { max: 20, message: 'Introduction cannot exceed 20 characters', trigger: 'blur' }
  ]
});

// 打开修改用户信息窗口
const showEditUserInfoDialog = (userInfo) => {
  if (userInfo) {
    formData.value = {
      nickName: userInfo.nickName || '',
      gender: userInfo.sex,
      personDescription: userInfo.personDescription || '',
      avatar: null
    };
    currentAvatarUrl.value = userInfo.avatar
  }

  dialogVisible.value = true;
};

defineExpose({ showEditUserInfoDialog });

// 头像上传相关
const localFile = ref(null);
const avatarPreview = ref(null); // 头像预览URL
const fileInputRef = ref(null); // 文件输入引用
const uploadingAvatar = ref(false); // 头像上传状态

// 当前用户头像URL
const currentAvatarUrl = ref("")

// 点击头像区域触发文件选择
const triggerFileInput = () => {
  fileInputRef.value.click();
};

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    // 验证文件类型
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
    if (!allowedTypes.includes(file.type)) {
      ElMessage.error('Please select image file')
      return;
    }

    // 验证文件大小（限制为5MB）
    const maxSize = 5 * 1024 * 1024;
    if (file.size > maxSize) {
      ElMessage.error('The image size cannot exceed 5MB')
      return
    }

    localFile.value = file;
    formData.value.avatar = file

    // 创建预览URL
    const reader = new FileReader();
    reader.onload = (e) => {
      avatarPreview.value = e.target.result
    };
    reader.readAsDataURL(file)
  }
};

// 上传头像
const uploadAvatar = async () => {
  if (!localFile.value) {
    return null;
  }

  uploadingAvatar.value = true;
  try {
    const formData = new FormData()
    formData.append('avatar', localFile.value)

    const response = await userAPI.uploadAvatar(formData);
    if (response.status === 'success') {
      ElMessage.success('Avatar uploaded successfully')
      return response.data.avatar
    }
  } catch (error) {
    console.log(error);
  } finally {
    uploadingAvatar.value = false;
  }
};

// 获取显示的头像URL
const getDisplayAvatarUrl = () => {
  return avatarPreview.value || currentAvatarUrl.value
};

// 提交状态
const submitting = ref(false);

// 提交表单
const submitForm = async () => {
  if (!formDataRef.value) return

  // 表单验证
  try {
    await formDataRef.value.validate();
  } catch (error) {
    ElMessage.error('Please check the form data')
    return;
  }

  submitting.value = true;

  try {
    let avatarUrl = null;

    // 如果有新头像，先上传头像
    if (localFile.value) {
      avatarUrl = await uploadAvatar()
    }

    // 准备更新数据
    const updateData = {
      nickName: formData.value.nickName,
      sex: formData.value.gender,
      personDescription: formData.value.personDescription
    };

    // 如果有新头像URL，添加到更新数据中
    if (avatarUrl) {
      updateData.avatar = avatarUrl;
    }

    // 调用更新用户信息API
    const response = await userStore.updateUserInfo(updateData);

    if (response.status === 'success') {
      dialogVisible.value = false

      // 通知父组件用户信息已更新
      emit('resetUserInfo', response.data)

      // 重置表单状态
      resetForm();

      // 延迟刷新页面，确保消息显示完成
      setTimeout(() => {
        window.location.reload()
      }, 1000);
    }
  } catch (error) {
    ElMessage.error('Failed to update user information')
  } finally {
    submitting.value = false
  }
};

// 重置表单
const resetForm = () => {
  localFile.value = null
  avatarPreview.value = null
  formData.value.avatar = null

  // 清空文件输入
  if (fileInputRef.value) {
    fileInputRef.value.value = ''
  }
};

// 取消编辑
const cancelEdit = () => {
  dialogVisible.value = false;
  resetForm();
};
</script>

<template>
  <el-dialog
      v-model="dialogVisible"
      title="Edit Personal Info"
      width="500"
      :showCancel="false"
  >
    <el-form :model="formData" :rules="formRules" ref="formDataRef" label-width="80px">
      <el-form-item label="Avatar" prop="avatar">
        <div class="avatar-upload-container">
          <!-- 头像显示区域 -->
          <div class="avatar-display" @click="triggerFileInput">
            <Avatar
              :src="getDisplayAvatarUrl()"
              :width="80"
              :addLink="false"
            />
            <div class="avatar-overlay">
              <el-icon class="upload-icon">
                <Camera />
              </el-icon>
              <span class="upload-text">Upload</span>
            </div>
          </div>

          <!-- 隐藏的文件输入 -->
          <input
            ref="fileInputRef"
            type="file"
            accept="image/*"
            @change="handleFileChange"
            style="display: none"
          />

          <!-- 提示信息 -->
          <div class="avatar-tips">
            <span class="tip-text">Image size not exceeding 5MB</span>
          </div>
        </div>
      </el-form-item>
      <!--昵称-->
      <el-form-item label="Nickname" prop="nickName">
        <el-input
            clearable
            :maxlength="8"
            show-word-limit
            placeholder="Please input nickname"
            v-model="formData.nickName"
        >
        </el-input>
      </el-form-item>
      <!-- 性别 -->
      <el-form-item label="Gender" prop="gender">
        <el-radio-group v-model="formData.gender">
          <el-radio :label="0">Male</el-radio>
          <el-radio :label="1">Female</el-radio>
        </el-radio-group>
      </el-form-item>
      <!--textarea输入-->
      <el-form-item label="Introduce" prop="personDescription">
        <el-input
            clearable
            placeholder="Please input introduction"
            :maxlength="20"
            show-word-limit
            v-model="formData.personDescription"
        ></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelEdit" :disabled="submitting">Cancel</el-button>
        <el-button
          type="primary"
          @click="submitForm"
          :loading="submitting"
          :disabled="submitting"
        >
          {{ submitting ? 'Saving...' : 'Save' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.avatar-upload-container {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 16px;
}

.avatar-display {
  position: relative;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  transition: all 0.3s ease;

  &:hover {
    .avatar-overlay {
      opacity: 1;
    }
  }
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  border-radius: 50%;

  .upload-icon {
    font-size: 24px;
    color: white;
    margin-bottom: 4px;
  }

  .upload-text {
    color: white;
    font-size: 12px;
  }
}


.avatar-tips {
  .tip-text {
    font-size: 12px;
    color: #909399;
    margin: 0;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  .avatar-upload-container {
    align-items: center;
    text-align: center;
  }

  .avatar-actions {
    flex-direction: column;
    width: 100%;

    .el-button {
      width: 100%;
    }
  }
}
</style>